package com.jie.flink.cdc.flinksink;

import com.jie.flink.cdc.doman.DataChangeInfo;
import com.jie.flink.cdc.util.JsonUtils;
import org.apache.flink.api.connector.sink2.SinkWriter;
import org.apache.flink.connector.elasticsearch.sink.ElasticsearchEmitter;
import org.apache.flink.connector.elasticsearch.sink.RequestIndexer;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.Map;

/**
 * @author zhanggj
 * @date 2023/3/14 17:08
 * @desc
 */
public class ElasticsearchEmitterImpl implements ElasticsearchEmitter<String> {
    @Override
    public void emit(final String element, final SinkWriter.Context context,
                     final RequestIndexer indexer) {
        DataChangeInfo dataChangeInfo = JsonUtils.stringToObject(element, DataChangeInfo.class);
        Map<String, Object> dataInfo = JsonUtils.toJSONMap(dataChangeInfo.getAfterData());
        indexer.add(Requests.indexRequest()
                .index("company_user_union")
                .id(dataInfo.get("company_id").toString())
                .source(JsonUtils.toJSONMap(dataChangeInfo.getAfterData()), XContentType.JSON));
    }
}
